package com.prs.crm.action.oa;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.Util;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.context.Constrains;
import com.prs.crm.context.FileUtil;
import com.prs.crm.context.ToolKits;
import com.prs.crm.domain.doc.DocLevel;
import com.prs.crm.domain.doc.DocType;
import com.prs.crm.domain.doc.Document;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.oa.JobPlan;
import com.prs.crm.domain.oa.JobPlanAssess;
import com.prs.crm.domain.oa.JobPlanCritique;
import com.prs.crm.domain.oa.JobPlanDetail;
import com.prs.crm.domain.oa.JobPlanType;
import com.prs.crm.domain.oa.OaTaskKeyWord;
import com.prs.crm.report.ReportUtils;
import com.prs.crm.service.doc.DocumentService;
import com.prs.crm.service.oa.JobPlanAssessService;
import com.prs.crm.service.oa.JobPlanCritiqueService;
import com.prs.crm.service.oa.JobPlanDetailService;
import com.prs.crm.service.oa.JobPlanService;
import com.prs.crm.service.oa.JobPlanTypeService;
import com.prs.crm.service.oa.OaTaskKeyWordService;

public class JobPlanAction extends BaseAction{
	private PaginationSupport pagination;
	
	private JobPlan jobPlan;
	private JobPlanCritique jobPlanCritique;
	private JobPlanAssess jobPlanAssess;
	private JobPlanService jobPlanService;
	private JobPlanDetailService jobPlanDetailService;
	private JobPlanCritiqueService jobPlanCritiqueService;
	private JobPlanAssessService jobPlanAssessService;
	private JobPlanTypeService jobPlanTypeService;
	private DocumentService  documentService;
	private Integer[] ids;

	private OaTaskKeyWordService OaTaskKeyWordService;
	private String selectDocFileName;
	public File upload;
	private String uploadFileName;
	private String copyToPersons;
	private String copyToPersonNames;
	private JobPlan lastJobPlan;
	private Collection<JobPlan> lastJobPlans;
	private static Collection<JobPlanDetail> jobPlanDetails;
	private Collection<Document> relatDocs;
	private JobPlanDetail jobPlanDetail;
	private String[] detailResults;
	private String jobPlanPercent;
	private String assessScores;
	private Collection<JobPlanCritique> jobPlanCritiques;
	private Collection<JobPlanType> jobPlanTypes;
	private String ymonth;
	
	private String[] names;
	private String[] codes;
	private DocType[] types;
	private String[] files;
	private DocLevel[] levels;
	private String[] keyWords;
	private String[] keyNames;

	static{
		jobPlanDetails = new ArrayList<JobPlanDetail>();
	}
	
	@Action("listMyExeDailyJobPlan")
	public String listMyExeDailyJobPlan() {
		Person person = AppContext.getAccountContext().currentUser();
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlan.class);
		criteria.add(Restrictions.eq("type", Constrains.JOBPLAN_DAILYPLAN));
		criteria.add(Restrictions.eq("recorder", person));
		criteria.add(Restrictions.eq("state", Constrains.TASK_EXECUTE));
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getJobPlanService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("listMyExeWeeklyJobPlan")
	public String listMyExeWeeklyJobPlan() {
		Person person = AppContext.getAccountContext().currentUser();
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlan.class);
		criteria.add(Restrictions.eq("type", Constrains.JOBPLAN_WEEKLYPLAN));
		criteria.add(Restrictions.eq("recorder", person));
		criteria.add(Restrictions.eq("state", Constrains.TASK_EXECUTE));
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getJobPlanService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("listMyExeMonthlyJobPlan")
	public String listMyExeMonthlyJobPlan() {
		Person person = AppContext.getAccountContext().currentUser();
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlan.class);
		criteria.add(Restrictions.eq("type", Constrains.JOBPLAN_MONTHLYPLAN));
		criteria.add(Restrictions.eq("recorder", person));
		criteria.add(Restrictions.eq("state", Constrains.TASK_EXECUTE));
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getJobPlanService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("listMyExeWilfullyJobPlan")
	public String listMyExeWilfullyJobPlan() {
		Person person = AppContext.getAccountContext().currentUser();
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlan.class);
		criteria.add(Restrictions.eq("type", Constrains.JOBPLAN_WILFULLYPLAN));
		criteria.add(Restrictions.eq("recorder", person));
		criteria.add(Restrictions.eq("state", Constrains.TASK_EXECUTE));
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getJobPlanService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("listMyAllJobPlan")
	public String listMyAllJobPlan() {
		return SUCCESS;
	}
	@Action("listMyAllJobPlanByMonth")
	public String listMyAllJobPlanByMonth(){
		Person person = AppContext.getAccountContext().currentUser();
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlan.class);
		criteria.add(Restrictions.eq("recorder", person));
		criteria.addOrder(Order.desc("type"));
		criteria.addOrder(Order.desc("recordTime"));
		Date start = null;
		Date end   = null;
		if(!"all".equals(ymonth)){
			if(ymonth != null){
				ymonth = ymonth.split(",")[0];
				if(ymonth.indexOf("-") == -1){
					start = ReportUtils.convertToDate(ymonth);
					end   = ReportUtils.convertToDate(String.valueOf(Integer.parseInt(ymonth) + 1));
				}else{
					start = ReportUtils.convertToDateFrom(ymonth);
					Calendar cal = Calendar.getInstance();
					cal.setTime(start);
					String s = String.valueOf(cal.get(Calendar.MONTH) + 2 > 12 ? "12" : "" + (cal.get(Calendar.MONTH) + 2));
					if(cal.get(Calendar.MONTH) + 2 > 12)
						end   = ReportUtils.convertToDate(String.valueOf(cal.get(Calendar.YEAR)), s, "31");
					else
						end   = ReportUtils.convertToDate(String.valueOf(cal.get(Calendar.YEAR)), s);
				}
			}
		}
		if(start != null && end != null){
			criteria.add(Restrictions.ge("startTime", start));
			criteria.add(Restrictions.lt("startTime", end));
		}
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getJobPlanService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("editDailyJobPlan")//sssssssssssssssssssssssssssssssdsd s
	public String editDailyJobPlan() {
		lastJobPlans = this.getJobPlanService().getLastJobPlan(Constrains.JOBPLAN_DAILYPLAN, AppContext.getAccountContext().currentUser(), Util.nowFullTime());
		jobPlanTypes = this.getJobPlanTypeService().getJobPlanTypeByType(Constrains.JOBPLAN_DAILYPLAN);
		if(lastJobPlans != null && lastJobPlans.size() == 1) {
			Object[] obj = lastJobPlans.toArray();
			lastJobPlan = (JobPlan) obj[0];
		}
		return SUCCESS;
	}
	
	@Action("editWeeklyJobPlan")
	public String editWeeklyJobPlan() {
		lastJobPlans = this.getJobPlanService().getLastJobPlan(Constrains.JOBPLAN_WEEKLYPLAN, AppContext.getAccountContext().currentUser(), Util.nowFullTime());
		jobPlanTypes = this.getJobPlanTypeService().getJobPlanTypeByType(Constrains.JOBPLAN_WEEKLYPLAN);
		if(lastJobPlans != null && lastJobPlans.size() == 1) {
			Object[] obj = lastJobPlans.toArray();
			lastJobPlan = (JobPlan) obj[0];
		}
		return SUCCESS;
	}
	
	@Action("editMonthlyJobPlan")
	public String editMonthlyJobPlan() {
		lastJobPlans = this.getJobPlanService().getLastJobPlan(Constrains.JOBPLAN_MONTHLYPLAN, AppContext.getAccountContext().currentUser(), Util.nowFullTime());
		jobPlanTypes = this.getJobPlanTypeService().getJobPlanTypeByType(Constrains.JOBPLAN_MONTHLYPLAN);
		if(lastJobPlans != null && lastJobPlans.size() == 1) {
			Object[] obj = lastJobPlans.toArray();
			lastJobPlan = (JobPlan) obj[0];
		}
		return SUCCESS;
	}
	
	@Action("editWilfullyJobPlan")
	public String editWilfullyJobPlan() {
		jobPlanTypes = this.getJobPlanTypeService().getJobPlanTypeByType(Constrains.JOBPLAN_WILFULLYPLAN);
		return SUCCESS;
	}
	
	@Action("listJobPlan")
	public String listJobPlan() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlan.class);
		criteria.addOrder(Order.desc("recordTime"));

		return SUCCESS;
	}
	
	@Action("viewJobPlan")
	public String viewJobPlan() {
		return SUCCESS;
	}
	//日计划                     
	@Clew(results={"success"})
	@Action(value="submitDailyJobPlan",results={@Result(name="success",type="redirect",location="listMyExeDailyJobPlan"),
			@Result(name="error",type="chain",location="editDailyJobPlan")})
	public String submitDailyJobPlan() {

		if(jobPlanDetails.size() == 0) {
			this.addActionError("计划明细不能为空");
			return ERROR;
		}
		if(jobPlan.getTitle() == null || jobPlan.getTitle().equals("")) {
			this.addActionError("计划主题不能为空");
			return ERROR;
		}
		if(jobPlan.getStartTime() == null) {
			this.addActionError("计划时间不能为空");
			return ERROR;
		}
		if(jobPlan.getAuditPerson() == null) {
			this.addActionError("主送对象不能为空");
			return ERROR;
		}
		if(this.getJobPlanService().existSameTimeJobPlan(jobPlan.getStartTime(), jobPlan.getEndTime(), Constrains.JOBPLAN_DAILYPLAN, AppContext.getAccountContext().currentUser())) {
			this.addActionError("已创建相同日期计划");
			return ERROR;
		}
		jobPlan.setType(Constrains.JOBPLAN_DAILYPLAN);
		jobPlan.setState(Constrains.TASK_EXECUTE);
		jobPlan.setPercent(0.0);
		jobPlan.setEndTime(jobPlan.getStartTime());
		this.getJobPlanService().submitJobPlan(jobPlanDetails,jobPlan,copyToPersons, upload, uploadFileName);
		jobPlanDetails.clear();
		
		relatDocs = new ArrayList<Document>();
		//任务文档
		for(int i=0;i<names.length;i++){
			Document  od=new Document();
			File StringToFile=new File(files[i]);			
			od.setName(names[i]);
			od.setDocumentcode(codes[i]);
			od.setLevel(levels[i]);
			od.setType(types[i]);
			String keyN=keyNames[i].replaceAll(","," ");
			od.setKeyWord(keyN);
			od.setAttach(FileUtil.getInstance().createAttach(StringToFile,StringToFile.getName()));

			
			relatDocs.add(od);
		}
		List<Document> rlist=(List<Document>) relatDocs;
		for(int o=0;o<rlist.size();o++){
			Document doc=rlist.get(o);
			String keyW[]=keyWords[o].split(",");
			for(int k=0;k<keyW.length;k++){
				OaTaskKeyWord Ootkw=this.getOaTaskKeyWordService().getOaTaskKeyWord(Integer.parseInt(keyW[k]));	
			doc.getOaTaskKeyWord().add(Ootkw);
			}
			doc.setId(null);
			doc.setJobPlan(jobPlan);
			this.getDocumentService().submitDocument(doc);
			
		}
		
		
		this.setPrompt("工作计划提交成功");
		return SUCCESS;
	}
	
	@Clew(results={"success"})
	@Action(value="submitWeeklyJobPlan",results={@Result(name="success",type="redirect",location="listMyExeWeeklyJobPlan"),
			@Result(name="error",type="chain",location="editWeeklyJobPlan")})
	public String submitWeeklyJobPlan() {
		if(jobPlanDetails.size() == 0) {
			this.addActionError("计划明细不能为空");
			return ERROR;
		}
		if(jobPlan.getTitle() == null || jobPlan.getTitle().equals("")) {
			this.addActionError("计划主题不能为空");
			return ERROR;
		}
		if(jobPlan.getStartTime() == null || jobPlan.getEndTime() == null) {
			this.addActionError("计划时间不能为空");
			return ERROR;
		}
		if(jobPlan.getAuditPerson() == null) {
			this.addActionError("主送对象不能为空");
			return ERROR;
		}
		if(this.getJobPlanService().existSameTimeJobPlan(jobPlan.getStartTime(), jobPlan.getEndTime(), Constrains.JOBPLAN_WEEKLYPLAN, AppContext.getAccountContext().currentUser())) {
			this.addActionError("已创建相同日期计划");
			return ERROR;
		}
		jobPlan.setType(Constrains.JOBPLAN_WEEKLYPLAN);
		jobPlan.setState(Constrains.TASK_EXECUTE);
		jobPlan.setPercent(0.0);
		this.getJobPlanService().submitJobPlan(jobPlanDetails,jobPlan,copyToPersons, upload, uploadFileName);
		jobPlanDetails.clear();
		
		//任务文档
		relatDocs = new ArrayList<Document>();
		for(int i=0;i<names.length;i++){
			Document  od=new Document();
			File StringToFile=new File(files[i]);			
			od.setName(names[i]);
			od.setDocumentcode(codes[i]);
			od.setLevel(levels[i]);
			od.setType(types[i]);
			String keyN=keyNames[i].replaceAll(","," ");
			od.setKeyWord(keyN);
			od.setAttach(FileUtil.getInstance().createAttach(StringToFile,StringToFile.getName()));
			relatDocs.add(od);
		}
		List<Document> rlist=(List<Document>) relatDocs;
		for(int o=0;o<rlist.size();o++){
			Document doc=rlist.get(o);
			String keyW[]=keyWords[o].split(",");
			for(int k=0;k<keyW.length;k++){
				OaTaskKeyWord Ootkw=this.getOaTaskKeyWordService().getOaTaskKeyWord(Integer.parseInt(keyW[k]));	
			doc.getOaTaskKeyWord().add(Ootkw);
			}
			doc.setId(null);
			doc.setJobPlan(jobPlan);
			this.getDocumentService().submitDocument(doc);
			
		}
		
		
		this.setPrompt("工作计划提交成功");
		return SUCCESS;
	}
	
	@Clew(results={"success"})
	@Action(value="submitMonthlyJobPlan",results={@Result(name="success",type="redirect",location="listMyExeMonthlyJobPlan"),
			@Result(name="error",type="chain",location="editMonthlyJobPlan")})
	public String submitMonthlyJobPlan() {
		if(jobPlanDetails.size() == 0) {
			this.addActionError("计划明细不能为空");
			return ERROR;
		}
		if(jobPlan.getTitle() == null || jobPlan.getTitle().equals("")) {
			this.addActionError("计划主题不能为空");
			return ERROR;
		}
		if(jobPlan.getStartTime() == null || jobPlan.getEndTime() == null) {
			this.addActionError("计划时间不能为空");
			return ERROR;
		}
		if(jobPlan.getAuditPerson() == null) {
			this.addActionError("主送对象不能为空");
			return ERROR;
		}
		if(this.getJobPlanService().existSameTimeJobPlan(jobPlan.getStartTime(), jobPlan.getEndTime(), Constrains.JOBPLAN_MONTHLYPLAN, AppContext.getAccountContext().currentUser())) {
			this.addActionError("已创建相同日期计划");
			return ERROR;
		}
		jobPlan.setType(Constrains.JOBPLAN_MONTHLYPLAN);
		jobPlan.setState(Constrains.TASK_EXECUTE);
		jobPlan.setPercent(0.0);
		this.getJobPlanService().submitJobPlan(jobPlanDetails,jobPlan,copyToPersons, upload, uploadFileName);
		jobPlanDetails.clear();
		//任务文档
		relatDocs = new ArrayList<Document>();
		for(int i=0;i<names.length;i++){
			Document  od=new Document();
			File StringToFile=new File(files[i]);			
			od.setName(names[i]);
			od.setDocumentcode(codes[i]);
			od.setLevel(levels[i]);
			od.setType(types[i]);
			String keyN=keyNames[i].replaceAll(","," ");
			od.setKeyWord(keyN);
			od.setAttach(FileUtil.getInstance().createAttach(StringToFile,StringToFile.getName()));
			relatDocs.add(od);
		}
		List<Document> rlist=(List<Document>) relatDocs;
		for(int o=0;o<rlist.size();o++){
			Document doc=rlist.get(o);
			String keyW[]=keyWords[o].split(",");
			for(int k=0;k<keyW.length;k++){
				OaTaskKeyWord Ootkw=this.getOaTaskKeyWordService().getOaTaskKeyWord(Integer.parseInt(keyW[k]));	
			doc.getOaTaskKeyWord().add(Ootkw);
			}
			doc.setId(null);
			doc.setJobPlan(jobPlan);
			this.getDocumentService().submitDocument(doc);
			
		}
		
		this.setPrompt("工作计划提交成功");
		return SUCCESS;
	}
	
	@Clew(results={"success"})
	@Action(value="submitWilfullyJobPlan",results={@Result(name="success",type="redirect",location="listMyExeWilfullyJobPlan"),
			@Result(name="error",type="chain",location="editWilfullyJobPlan")})
	public String submitWilfullyJobPlan() {
		if(jobPlanDetails.size() == 0) {
			this.addActionError("计划明细不能为空");
			return ERROR;
		}
		if(jobPlan.getTitle() == null || jobPlan.getTitle().equals("")) {
			this.addActionError("计划主题不能为空");
			return ERROR;
		}
		if(jobPlan.getStartTime() == null || jobPlan.getEndTime() == null) {
			this.addActionError("计划时间不能为空");
			return ERROR;
		}
		if(jobPlan.getAuditPerson() == null) {
			this.addActionError("主送对象不能为空");
			return ERROR;
		}
		if(this.getJobPlanService().existSameTimeJobPlan(jobPlan.getStartTime(), jobPlan.getEndTime(), Constrains.JOBPLAN_WILFULLYPLAN, AppContext.getAccountContext().currentUser())) {
			this.addActionError("已创建相同日期计划");
			return ERROR;
		}
		jobPlan.setType(Constrains.JOBPLAN_WILFULLYPLAN);
		jobPlan.setState(Constrains.TASK_EXECUTE);
		jobPlan.setPercent(0.0);
		this.getJobPlanService().submitJobPlan(jobPlanDetails,jobPlan,copyToPersons, upload, uploadFileName);
		jobPlanDetails.clear();
		//任务文档
		relatDocs = new ArrayList<Document>();
		for(int i=0;i<names.length;i++){
			Document  od=new Document();
			File StringToFile=new File(files[i]);			
			od.setName(names[i]);
			od.setDocumentcode(codes[i]);
			od.setLevel(levels[i]);
			od.setType(types[i]);
			String keyN=keyNames[i].replaceAll(","," ");
			od.setKeyWord(keyN);
			od.setAttach(FileUtil.getInstance().createAttach(StringToFile,StringToFile.getName()));
			relatDocs.add(od);
		}
		List<Document> rlist=(List<Document>) relatDocs;
		for(int o=0;o<rlist.size();o++){
			Document doc=rlist.get(o);
			String keyW[]=keyWords[o].split(",");
			for(int k=0;k<keyW.length;k++){
				OaTaskKeyWord Ootkw=this.getOaTaskKeyWordService().getOaTaskKeyWord(Integer.parseInt(keyW[k]));	
			doc.getOaTaskKeyWord().add(Ootkw);
			}
			doc.setId(null);
			doc.setJobPlan(jobPlan);
			this.getDocumentService().submitDocument(doc);
			
		}
		
		this.setPrompt("工作计划提交成功");
		return SUCCESS;
	}
	
	@Action(value="appendDailyJobPlanDetail",results={@Result(name="success",type="chain",location="editDailyJobPlan")})
	public String appendDailyJobPlanDetail() {
		JobPlanDetail detial = new JobPlanDetail();
		detial.setId(jobPlanDetails.size());
		detial.setSummary(jobPlanDetail.getSummary());
		detial.setType(jobPlanDetail.getType());
		jobPlanDetails.add(detial);

		return SUCCESS;
	}
	
	@Action(value="deleteDailyJobPlanDetail",results={@Result(name="success",type="chain",location="editDailyJobPlan"),
			@Result(name="error",type="chain",location="editDailyJobPlan")})
	public String deleteDailyJobPlanDetail() {
		if(ids == null) {
			this.addActionError("请选择要删除的计划明细");
			return ERROR;
		}
		
		for(Integer id : ids) {
			Iterator<JobPlanDetail> iter = jobPlanDetails.iterator();
			while(iter.hasNext()) {
				JobPlanDetail detial = iter.next();
				if(detial.getId().intValue() == id.intValue()) {					
					jobPlanDetails.remove(detial);
					break;
				}
			}
		}
		
		return SUCCESS;
	}
	
	@Action(value="appendWeeklyJobPlanDetail",results={@Result(name="success",type="chain",location="editWeeklyJobPlan")})
	public String appendWeeklyJobPlanDetail() {
		JobPlanDetail detial = new JobPlanDetail();
		detial.setId(jobPlanDetails.size());
		detial.setSummary(jobPlanDetail.getSummary());
		detial.setType(jobPlanDetail.getType());
		jobPlanDetails.add(detial);
		return SUCCESS;
	}
	
	@Action(value="deleteWeeklyJobPlanDetail",results={@Result(name="success",type="chain",location="editWeeklyJobPlan"),
			@Result(name="error",type="chain",location="editWeeklyJobPlan")})
	public String deleteWeeklyJobPlanDetail() {
		if(ids == null) {
			this.addActionError("请选择要删除的计划明细");
			return ERROR;
		}
		
		for(Integer id : ids) {
			Iterator<JobPlanDetail> iter = jobPlanDetails.iterator();
			while(iter.hasNext()) {
				JobPlanDetail detial = iter.next();
				if(detial.getId().intValue() == id.intValue()) {
					jobPlanDetails.remove(detial);
					break;
				}
			}
		}
		
		return SUCCESS;
	}
	
	@Action(value="appendMonthlyJobPlanDetail",results={@Result(name="success",type="chain",location="editMonthlyJobPlan")})
	public String appendMonthlyJobPlanDetail() {
		JobPlanDetail detial = new JobPlanDetail();
		detial.setId(jobPlanDetails.size());
		detial.setSummary(jobPlanDetail.getSummary());
		detial.setType(jobPlanDetail.getType());
		jobPlanDetails.add(detial);
		return SUCCESS;
	}
	
	@Action(value="deleteMonthlyJobPlanDetail",results={@Result(name="success",type="chain",location="editMonthlyJobPlan"),
			@Result(name="error",type="chain",location="editMonthlyJobPlan")})
	public String deleteMonthlyJobPlanDetail() {
		if(ids == null) {
			this.addActionError("请选择要删除的计划明细");
			return ERROR;
		}
		
		for(Integer id : ids) {
			Iterator<JobPlanDetail> iter = jobPlanDetails.iterator();
			while(iter.hasNext()) {
				JobPlanDetail detial = iter.next();
				if(detial.getId().intValue() == id.intValue()) {
					jobPlanDetails.remove(detial);
					break;
				}
			}
		}
		
		return SUCCESS;
	}
	
	@Action(value="appendWilfullyJobPlanDetail",results={@Result(name="success",type="chain",location="editWilfullyJobPlan")})
	public String appendWilfullyJobPlanDetail() {
		JobPlanDetail detial = new JobPlanDetail();
		detial.setId(jobPlanDetails.size());
		detial.setSummary(jobPlanDetail.getSummary());
		detial.setType(jobPlanDetail.getType());
		jobPlanDetails.add(detial);
		return SUCCESS;
	}
	
	@Action(value="deleteWilfullyJobPlanDetail",results={@Result(name="success",type="chain",location="editWilfullyJobPlan"),
			@Result(name="error",type="chain",location="editWilfullyJobPlan")})
	public String deleteWilfullyJobPlanDetail() {
		if(ids == null) {
			this.addActionError("请选择要删除的计划明细");
			return ERROR;
		}
		
		for(Integer id : ids) {
			Iterator<JobPlanDetail> iter = jobPlanDetails.iterator();
			while(iter.hasNext()) {
				JobPlanDetail detial = iter.next();
				if(detial.getId().intValue() == id.intValue()) {
					jobPlanDetails.remove(detial);
					break;
				}
			}
		}
		
		return SUCCESS;
	}
	
	@Action("listCritiqueJobPlan")
	public String listCritiqueJobPlan() {
		Person person = AppContext.getAccountContext().currentUser();
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlan.class);
		criteria.add(Restrictions.ne("state", Constrains.TASK_PASS));
		criteria.createAlias("copyToPersons", "c");
		criteria.add(Restrictions.eq("c.id", person.getId()));
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getJobPlanService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("listFinishCritiqueJobPlan")
	public String listFinishCritiqueJobPlan() {
		Person person = AppContext.getAccountContext().currentUser();
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlan.class);
		criteria.add(Restrictions.eq("state", Constrains.TASK_PASS));
		criteria.createAlias("copyToPersons", "c");
		criteria.add(Restrictions.eq("c.id", person.getId()));
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getJobPlanService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("listAllCritiqueJobPlan")
	public String listAllCritiqueJobPlan() {
		return SUCCESS;
	}
	@Action("listAllCritiqueJobPlanByMonth")
	public String listAllCritiqueJobPlanByMonth(){
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlanCritique.class);
		criteria.addOrder(Order.desc("recordTime"));
		Date start = null;
		Date end   = null;
		if(!"all".equals(ymonth)){
			if(ymonth != null){
				ymonth = ymonth.split(",")[0];
				if(ymonth.indexOf("-") == -1){
					start = ReportUtils.convertToDate(ymonth);
					end   = ReportUtils.convertToDate(String.valueOf(Integer.parseInt(ymonth) + 1));
				}else{
					start = ReportUtils.convertToDateFrom(ymonth);
					Calendar cal = Calendar.getInstance();
					cal.setTime(start);
					String s = String.valueOf(cal.get(Calendar.MONTH) + 2 > 12 ? "12" : "" + (cal.get(Calendar.MONTH) + 2));
					if(cal.get(Calendar.MONTH) + 2 > 12)
						end   = ReportUtils.convertToDate(String.valueOf(cal.get(Calendar.YEAR)), s, "31");
					else
						end   = ReportUtils.convertToDate(String.valueOf(cal.get(Calendar.YEAR)), s);
				}
			}
		}
		if(start != null && end != null){
			criteria.createAlias("jobPlan", "jp");
			criteria.add(Restrictions.ge("jp.startTime", start));
			criteria.add(Restrictions.lt("jp.startTime", end));
		}
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getJobPlanCritiqueService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	
	@Action("critiqueJobPlan")
	public String critiqueJobPlan() {
		jobPlanCritiques = this.getJobPlanCritiqueService().getJobPlanCritiqueByJobPlan(jobPlan);
		return SUCCESS;
	}
	
	@Action("viewJobPlanCritique")
	public String viewJobPlanCritique() {
		jobPlanCritiques = this.getJobPlanCritiqueService().getJobPlanCritiqueByJobPlan(jobPlan);
		return SUCCESS;
	}
	
	@Action("listAssessJobPlan")
	public String listAssessJobPlan() {
		Person person = AppContext.getAccountContext().currentUser();		
		Collection<JobPlan> jobPlans = this.getJobPlanService().getJobPlanByAudit(person);
		pagination = this.getPaginationHelper().prepare(pagination);
		List<JobPlan> results = new ArrayList<JobPlan>();
		for(JobPlan jobPlan : jobPlans) {
			if(jobPlan.getJobPlanAssess() == null) {
				results.add(jobPlan);
			}
		}
		pagination.setTotalCount(results.size());
		int totalPage = pagination.getTotalCount() / pagination.getPageSize();
        if(totalPage * pagination.getPageSize() < pagination.getTotalCount())
              totalPage++;
        pagination.setTotalPage(totalPage);
        pagination.setItems(results);
		return SUCCESS;
	}
	
	@Action("listFinishAssessJobPlan")
	public String listFinishAssessJobPlan() {
		return SUCCESS;		
	}
	@Action("listFinishAssessJobPlanByMonth")
	public String listFinishAssessJobPlanByMonth(){
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlanAssess.class);
		criteria.add(Restrictions.eq("recorder", AppContext.getAccountContext().currentUser()));
		criteria.addOrder(Order.desc("recordTime"));
		Date start = null;
		Date end   = null;
		if(!"all".equals(ymonth)){
			if(ymonth != null){
				ymonth = ymonth.split(",")[0];
				if(ymonth.indexOf("-") == -1){
					start = ReportUtils.convertToDate(ymonth);
					end   = ReportUtils.convertToDate(String.valueOf(Integer.parseInt(ymonth) + 1));
				}else{
					start = ReportUtils.convertToDateFrom(ymonth);
					Calendar cal = Calendar.getInstance();
					cal.setTime(start);
					String s = String.valueOf(cal.get(Calendar.MONTH) + 2 > 12 ? "12" : "" + (cal.get(Calendar.MONTH) + 2));
					if(cal.get(Calendar.MONTH) + 2 > 12)
						end   = ReportUtils.convertToDate(String.valueOf(cal.get(Calendar.YEAR)), s, "31");
					else
						end   = ReportUtils.convertToDate(String.valueOf(cal.get(Calendar.YEAR)), s);
				}
			}
		}
		if(start != null && end != null){
			criteria.createAlias("jobPlan", "jp");
			criteria.add(Restrictions.ge("jp.startTime", start));
			criteria.add(Restrictions.lt("jp.startTime", end));
		}
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getJobPlanAssessService().listByPage(criteria, pagination));
		return SUCCESS;		
	}
	
	
	@Action("listAllAssessJobPlan")
	public String listAllAssessJobPlan() {
		return SUCCESS;
	}
	@Action("listAllAssessJobPlanByMonth")
	public String listAllAssessJobPlanByMonth(){
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(JobPlanAssess.class);
		criteria.addOrder(Order.desc("recordTime"));
		Date start = null;
		Date end   = null;
		if(!"all".equals(ymonth)){
			if(ymonth != null){
				ymonth = ymonth.split(",")[0];
				if(ymonth.indexOf("-") == -1){
					start = ReportUtils.convertToDate(ymonth);
					end   = ReportUtils.convertToDate(String.valueOf(Integer.parseInt(ymonth) + 1));
				}else{
					start = ReportUtils.convertToDateFrom(ymonth);
					Calendar cal = Calendar.getInstance();
					cal.setTime(start);
					String s = String.valueOf(cal.get(Calendar.MONTH) + 2 > 12 ? "12" : "" + (cal.get(Calendar.MONTH) + 2));
					if(cal.get(Calendar.MONTH) + 2 > 12)
						end   = ReportUtils.convertToDate(String.valueOf(cal.get(Calendar.YEAR)), s, "31");
					else
						end   = ReportUtils.convertToDate(String.valueOf(cal.get(Calendar.YEAR)), s);
				}
			}
		}
		if(start != null && end != null){
			criteria.createAlias("jobPlan", "jp");
			criteria.add(Restrictions.ge("jp.startTime", start));
			criteria.add(Restrictions.lt("jp.startTime", end));
		}
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getJobPlanAssessService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("assessJobPlan")
	public String assessJobPlan() {
		jobPlanCritiques = this.getJobPlanCritiqueService().getJobPlanCritiqueByJobPlan(jobPlan);
		return SUCCESS;
	}
	
	@Action("viewAssessJobPlan")
	public String viewAssessJobPlan() {
		jobPlanCritiques = this.getJobPlanCritiqueService().getJobPlanCritiqueByJobPlan(jobPlanAssess.getJobPlan());
		return SUCCESS;
	}
	
	@Clew(results={"success"})
	@Action(value="submitAssessJobPlan",results={@Result(name="success",type="redirect",location="listAssessJobPlan"),
			@Result(name="error",type="chain",location="assessJobPlan")})
	public String submitAssessJobPlan() {
		if(this.getAssessScores() == null) {
			this.addActionError("请输入评定分数");
			return ERROR;
		}
		if(!ToolKits.isNumeric(this.getAssessScores())) {
			this.addActionError("评定分数应为数字");
			return ERROR;
		}
		jobPlanAssess.setScores(Double.valueOf(this.getAssessScores()));
		jobPlanAssess.setJobPlan(jobPlan);
		this.getJobPlanAssessService().submitJobPlanAssess(jobPlanAssess, upload, uploadFileName);
		this.setPrompt("提交工作计划点评成功");
		return SUCCESS;
	}
	
	@Clew(results={"success"})
	@Action(value="submitCritiqueJobPlan",results={@Result(name="success",type="redirect",location="listCritiqueJobPlan")})
	public String submitCritiqueJobPlan() {
//		String type = jobPlanCritique.getType();
//		if(type.equals("仅主送人")) {
//			jobPlanCritique.setType(Constrains.CRITIQUE_LEVEL_1);
//		}else if(type.equals("主送人和点评人")) {
//			jobPlanCritique.setType(Constrains.CRITIQUE_LEVEL_2);
//		}else if(type.equals("所有人")) {
//			jobPlanCritique.setType(Constrains.CRITIQUE_LEVEL_3);
//		}
		jobPlanCritique.setJobPlan(jobPlan);
		this.getJobPlanCritiqueService().saveJobPlanCritique(jobPlanCritique, upload, uploadFileName);
			
		this.setPrompt("提交工作计划点评成功");
		return SUCCESS;
	}
	
	@Action("executeJobPlan")
	public String executeJobPlan() {
		jobPlanPercent = String.valueOf(jobPlan.getPercent());
		return SUCCESS;
	}
	
	@Clew(results={"daily","weekly","monthly","wilfully"})
	@Action(value="submitExecuteJobPlan",results={@Result(name="daily",type="redirect",location="listMyExeDailyJobPlan"),
			@Result(name="weekly",type="redirect",location="listMyExeWeeklyJobPlan"),
			@Result(name="monthly",type="redirect",location="listMyExeMonthlyJobPlan"),
			@Result(name="wilfully",type="redirect",location="listMyExeWilfullyJobPlan"),
			@Result(name="error",type="chain",location="executeJobPlan")})
	public String submitExecuteJobPlan() {
		int count = 0;
		for(Integer id : ids) {
			String result = detailResults[count];
			JobPlanDetail detial = this.getJobPlanDetailService().get(id);
			if(result.equals("等待")) {
				detial.setState(Constrains.TASK_WAIT);
			}
			else if(result.equals("执行")) {
				detial.setState(Constrains.TASK_EXECUTE);
			}
			else if(result.equals("完成")) {
				detial.setState(Constrains.TASK_PASS);
			}
			this.getJobPlanDetailService().save(detial);
			count ++;
		}
		
		if(ToolKits.isNumeric(jobPlanPercent)) {
			Double percent = Double.parseDouble(jobPlanPercent);
			if(percent <= 100) {
				jobPlan.setPercent(percent);
				this.getJobPlanService().save(jobPlan);
			}
			else {
				this.addActionError("计划完成量应为100以内的数字");
				return ERROR;
			}
		}else {
			this.addActionError("计划完成量应为100以内的数字");
			return ERROR;
		}
		
		boolean flag = true;
		Collection<JobPlanDetail> details = this.getJobPlanDetailService().getJobPlanDetailByJobPlan(jobPlan);
		for(JobPlanDetail detail : details) {
			if(!detail.getState().equals(Constrains.TASK_PASS)) {
				flag = false;
				break;
			}
		}
		if(flag) {
			jobPlan.setState(Constrains.TASK_PASS);
			this.getJobPlanService().save(jobPlan);
			
			this.setPrompt("工作计划执行完成，提交成功");
		}else {
			this.setPrompt("工作计划未执行完成，保存成功");
		}
		
		if(jobPlan.getType().equals(Constrains.JOBPLAN_DAILYPLAN)) {
			return "daily";
		}else if(jobPlan.getType().equals(Constrains.JOBPLAN_WEEKLYPLAN)){
			return "weekly";
		}else if(jobPlan.getType().equals(Constrains.JOBPLAN_MONTHLYPLAN)){
			return "monthly";
		}else if(jobPlan.getType().equals(Constrains.JOBPLAN_WEEKLYPLAN)){
			return "wilfully";
		}
			
		return SUCCESS;
	}
	
	public JobPlan getJobPlan() {
		return jobPlan;
	}
	public void setJobPlan(JobPlan jobPlan) {
		this.jobPlan = jobPlan;
	}
	public JobPlanService getJobPlanService() {
		return jobPlanService;
	}
	public void setJobPlanService(JobPlanService jobPlanService) {
		this.jobPlanService = jobPlanService;
	}

	public Integer[] getIds() {
		return ids;
	}
	public void setIds(Integer[] ids) {
		this.ids = ids;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}

	public File getUpload() {
		return upload;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setCopyToPersons(String copyToPersons) {
		this.copyToPersons = copyToPersons;
	}

	public String getCopyToPersons() {
		return copyToPersons;
	}

	public void setLastJobPlan(JobPlan lastJobPlan) {
		this.lastJobPlan = lastJobPlan;
	}

	public JobPlan getLastJobPlan() {
		return lastJobPlan;
	}

	public void setLastJobPlans(Collection<JobPlan> lastJobPlans) {
		this.lastJobPlans = lastJobPlans;
	}

	public Collection<JobPlan> getLastJobPlans() {
		return lastJobPlans;
	}

	public void setJobPlanDetails(Collection<JobPlanDetail> jobPlanDetails) {
		this.jobPlanDetails = jobPlanDetails;
	}

	public Collection<JobPlanDetail> getJobPlanDetails() {
		return jobPlanDetails;
	}

	public void setJobPlanDetail(JobPlanDetail jobPlanDetail) {
		this.jobPlanDetail = jobPlanDetail;
	}

	public JobPlanDetail getJobPlanDetail() {
		return jobPlanDetail;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setDetailResults(String[] detailResults) {
		this.detailResults = detailResults;
	}

	public String[] getDetailResults() {
		return detailResults;
	}

	public void setJobPlanDetailService(JobPlanDetailService jobPlanDetailService) {
		this.jobPlanDetailService = jobPlanDetailService;
	}

	public JobPlanDetailService getJobPlanDetailService() {
		return jobPlanDetailService;
	}

	public void setJobPlanPercent(String jobPlanPercent) {
		this.jobPlanPercent = jobPlanPercent;
	}

	public String getJobPlanPercent() {
		return jobPlanPercent;
	}

	public void setJobPlanCritique(JobPlanCritique jobPlanCritique) {
		this.jobPlanCritique = jobPlanCritique;
	}

	public JobPlanCritique getJobPlanCritique() {
		return jobPlanCritique;
	}

	public void setJobPlanCritiqueService(JobPlanCritiqueService jobPlanCritiqueService) {
		this.jobPlanCritiqueService = jobPlanCritiqueService;
	}

	public JobPlanCritiqueService getJobPlanCritiqueService() {
		return jobPlanCritiqueService;
	}

	public void setJobPlanCritiques(Collection<JobPlanCritique> jobPlanCritiques) {
		this.jobPlanCritiques = jobPlanCritiques;
	}

	public Collection<JobPlanCritique> getJobPlanCritiques() {
		return jobPlanCritiques;
	}

	public void setJobPlanAssessService(JobPlanAssessService jobPlanAssessService) {
		this.jobPlanAssessService = jobPlanAssessService;
	}

	public JobPlanAssessService getJobPlanAssessService() {
		return jobPlanAssessService;
	}

	public JobPlanAssess getJobPlanAssess() {
		return jobPlanAssess;
	}

	public void setJobPlanAssess(JobPlanAssess jobPlanAssess) {
		this.jobPlanAssess = jobPlanAssess;
	}

	public void setAssessScores(String assessScores) {
		this.assessScores = assessScores;
	}

	public String getAssessScores() {
		return assessScores;
	}

	public void setJobPlanTypeService(JobPlanTypeService jobPlanTypeService) {
		this.jobPlanTypeService = jobPlanTypeService;
	}

	public JobPlanTypeService getJobPlanTypeService() {
		return jobPlanTypeService;
	}

	public void setJobPlanTypes(Collection<JobPlanType> jobPlanTypes) {
		this.jobPlanTypes = jobPlanTypes;
	}

	public Collection<JobPlanType> getJobPlanTypes() {
		return jobPlanTypes;
	}

	public void setCopyToPersonNames(String copyToPersonNames) {
		this.copyToPersonNames = copyToPersonNames;
	}

	public String getCopyToPersonNames() {
		return copyToPersonNames;
	}

	public String getYmonth() {
		return ymonth;
	}

	public void setYmonth(String ymonth) {
		this.ymonth = ymonth;
	}

	public String[] getNames() {
		return names;
	}

	public void setNames(String[] names) {
		this.names = names;
	}

	public String[] getCodes() {
		return codes;
	}

	public void setCodes(String[] codes) {
		this.codes = codes;
	}

	public DocType[] getTypes() {
		return types;
	}

	public void setTypes(DocType[] types) {
		this.types = types;
	}

	public String[] getFiles() {
		return files;
	}

	public void setFiles(String[] files) {
		this.files = files;
	}

	public DocLevel[] getLevels() {
		return levels;
	}

	public void setLevels(DocLevel[] levels) {
		this.levels = levels;
	}

	public Collection<Document> getRelatDocs() {
		return relatDocs;
	}

	public void setRelatDocs(Collection<Document> relatDocs) {
		this.relatDocs = relatDocs;
	}

	public DocumentService getDocumentService() {
		return documentService;
	}

	public void setDocumentService(DocumentService documentService) {
		this.documentService = documentService;
	}

	public String getSelectDocFileName() {
		return selectDocFileName;
	}

	public void setSelectDocFileName(String selectDocFileName) {
		this.selectDocFileName = selectDocFileName;
	}

	public String[] getKeyWords() {
		return keyWords;
	}

	public void setKeyWords(String[] keyWords) {
		this.keyWords = keyWords;
	}

	public String[] getKeyNames() {
		return keyNames;
	}

	public void setKeyNames(String[] keyNames) {
		this.keyNames = keyNames;
	}

	public OaTaskKeyWordService getOaTaskKeyWordService() {
		return OaTaskKeyWordService;
	}

	public void setOaTaskKeyWordService(OaTaskKeyWordService oaTaskKeyWordService) {
		OaTaskKeyWordService = oaTaskKeyWordService;
	}

}
